package com.jzg.jcptadmin.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.jzg.jcptadmin.R;
import com.jzg.jcptadmin.Utils.MyToast;
import com.jzg.jcptadmin.Utils.NoDoubleClick;
import com.jzg.jcptadmin.Utils.ScreenUtils;
import com.jzg.jcptadmin.Utils.StringUtils;
import com.jzg.jcptadmin.app.ActivityHelp;
import com.jzg.jcptadmin.base.BaseActivity;
import com.jzg.jcptadmin.constant.Constant;
import com.jzg.jcptadmin.data.DataManager;
import com.jzg.jcptadmin.data.vo.CarConfigModel;
import com.jzg.jcptadmin.data.vo.CarDetails;
import com.jzg.jcptadmin.data.vo.CarTypeModel;
import com.jzg.jcptadmin.presenter.CarConfigSelectPresenter;
import com.jzg.jcptadmin.presenter.CarTypeSelectPresenter;
import com.jzg.jcptadmin.view.CustomRippleButton;
import com.jzg.jcptadmin.view.MarqueeText;
import com.jzg.jcptadmin.view.SheetTimeAty;
import com.jzg.jcptadmin.viewinterface.CarConfigSelectInterface;
import com.jzg.jcptadmin.viewinterface.CarTypeSelectInterface;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 *
 * @author zealjiang
 * @time 2017/3/17 15:15
 */
public class CarTypeSelectActivity extends BaseActivity implements CarTypeSelectInterface,CarConfigSelectInterface {

    @Bind(R.id.title_content)
    TextView inputTopText;
    @Bind(R.id.tv_right)
    TextView tvRight;
    @Bind(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    @Bind(R.id.rlBrandSeries)
    RelativeLayout rlBrandSeries;
    @Bind(R.id.tvBrandSeriesValue)
    MarqueeText tvBrandSeriesValue;
    @Bind(R.id.tvHintError)
    TextView tvHintError;
    @Bind(R.id.llCarConfig)
    LinearLayout llCarConfig;
    @Bind(R.id.crbNext)
    CustomRippleButton crbNext;
    @Bind(R.id.btnNextError)
    Button btnNextError;
    @Bind(R.id.rlProductDate)
    RelativeLayout rlProductDate;
    @Bind(R.id.tvProductDate)
    TextView tvProductDate;
    @Bind(R.id.tagflow_gear)
    TagFlowLayout tagFlowGear;
    @Bind(R.id.tagflow_driving_mode)
    TagFlowLayout tagFlowDrivingMode;
    @Bind(R.id.tagflow_displacement)
    TagFlowLayout tagFlowDisplacement;
    @Bind(R.id.tvRetry)
    TextView tvRetry;

    private CarTypeSelectActivity self;
    private final int REQUEST_BRAND_SEREIS = 10;//品牌车系请求码

    private CarTypeSelectPresenter carTypeSelectPresenter;
    private CarConfigSelectPresenter carConfigSelectPresenter;
    private CarDetails details;
    private CarTypeModel.DataBean carTypeBean;
    private int currentYear;
    private int currentMonth;
    private int MinYEAR;

    private ArrayList<String> gearList = new ArrayList<>();
    private ArrayList<String> drivingModeList = new ArrayList<>();
    private ArrayList<String> displacementList = new ArrayList<>();

    private TagAdapter tagAdapterGear;
    private TagAdapter tagAdapterDrivingMode;
    private TagAdapter tagAdapterDisplacement;

    private CarConfigModel carConfigModel;
    private String gearSelected;//变速箱当前选中项
    private String drivingModeSelected;//驱动方式当前选中项
    private String displacementSelected;//排气量当前选中项
    private ArrayList<String> selectedCondition = new ArrayList<String>();//查询条件，有先后顺序之分

    private NoDoubleClick noDoubleClick;
    private String vin;
    private String plateType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_car_type_select);
        self = this;
        ButterKnife.bind(this);
        inputTopText.setText("车型选择");
        tvRight.setText("直接选车");

        vin = getIntent().getStringExtra("vin");
        plateType = getIntent().getStringExtra("plateType");
        details = getIntent().getParcelableExtra("details");

        //防重击
        noDoubleClick = new NoDoubleClick();

        carTypeSelectPresenter = new CarTypeSelectPresenter(DataManager.getInstance());
        carTypeSelectPresenter.attachView(this);

        //配置
        carConfigSelectPresenter = new CarConfigSelectPresenter(DataManager.getInstance());
        carConfigSelectPresenter.attachView(this);

        //轮滑图
        ViewGroup.LayoutParams params = convenientBanner.getLayoutParams();
        params.width = RadioGroup.LayoutParams.MATCH_PARENT;
        params.height = ScreenUtils.getScreenWidth(this) * 9 / 16;
        convenientBanner.setLayoutParams(params);
        setPicAdapter();

        //出厂日期
        getCurrentDate();

        initCarConfig();

        //网络请求
        carTypeSelectPresenter.getCarTypes(vin,plateType);

    }

    private void initCarConfig(){

        final LayoutInflater mInflater = LayoutInflater.from(this.getApplicationContext());

        //变速箱
        tagAdapterGear = new TagAdapter<String>(gearList)
        {
            @Override
            public View getView(FlowLayout parent, int position, String s)
            {
                TextView tv = (TextView) mInflater.inflate(R.layout.tag_car_config, tagFlowGear, false);
                tv.setText(s);
                return tv;
            }
        };
        tagFlowGear.setAdapter(tagAdapterGear);
        tagFlowGear.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
        {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent)
            {
                //Toast.makeText(CarConfigSelectView.this.getContext(), gearList.get(position), Toast.LENGTH_SHORT).show();
                String gearSelected = gearList.get(position);
                if(gearSelected.equals(self.gearSelected)){
                    //如果包含此条件，则去除此条件
                    for (int i = 0; i < selectedCondition.size(); i++) {
                        if(selectedCondition.get(i).startsWith("变速箱:")){
                            selectedCondition.remove(i);
                            break;
                        }
                    }

                    //将选中状态置为未选中状态并重置所有选项(所有选项中保持之前的选中状态)
                    self.gearSelected = "";

                    setConfigListBySelection(selectedCondition);
                    setSelectedList();
                    refresh();
                }else{
                    //如果不包含此条件，则添加此条件
                    boolean has = false;
                    for (int i = 0; i < selectedCondition.size(); i++) {
                        if(selectedCondition.get(i).startsWith("变速箱:")){
                            has = true;
                            break;
                        }
                    }
                    if(!has){
                        selectedCondition.add("变速箱:"+gearSelected);
                    }

                    self.gearSelected = gearSelected;
                    //getConfigByGear(gearSelected);

                    setConfigListBySelection(selectedCondition);
                    setSelectedList();
                    refresh();
                }
                return true;
            }
        });

        //驱动方式
        tagAdapterDrivingMode = new TagAdapter<String>(drivingModeList)
        {
            @Override
            public View getView(FlowLayout parent, int position, String s)
            {
                TextView tv = (TextView) mInflater.inflate(R.layout.tag_car_config, tagFlowDrivingMode, false);
                tv.setText(s);
                return tv;
            }
        };
        tagFlowDrivingMode.setAdapter(tagAdapterDrivingMode);
        tagFlowDrivingMode.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
        {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent)
            {
                //Toast.makeText(CarConfigSelectView.this.getContext(), drivingModeList.get(position), Toast.LENGTH_SHORT).show();
                String drivingModeSelected = drivingModeList.get(position);
                if(drivingModeSelected.equals(self.drivingModeSelected)){
                    //如果包含此条件，则去除此条件
                    for (int i = 0; i < selectedCondition.size(); i++) {
                        if(selectedCondition.get(i).startsWith("驱动方式:")){
                            selectedCondition.remove(i);
                            break;
                        }
                    }

                    //将选中状态置为未选中状态并重置所有选项(所有选项中保持之前的选中状态)
                    self.drivingModeSelected = "";
                    //resetConfig(self.drivingModeSelected);

                    setConfigListBySelection(selectedCondition);
                    setSelectedList();
                    refresh();
                }else{
                    //如果不包含此条件，则添加此条件
                    boolean has = false;
                    for (int i = 0; i < selectedCondition.size(); i++) {
                        if(selectedCondition.get(i).startsWith("驱动方式:")){
                            has = true;
                            break;
                        }
                    }
                    if(!has){
                        selectedCondition.add("驱动方式:"+drivingModeSelected);
                    }

                    self.drivingModeSelected = drivingModeSelected;
                    //getConfigByDrivingMode(drivingModeSelected);

                    setConfigListBySelection(selectedCondition);
                    setSelectedList();
                    refresh();
                }
                return true;
            }
        });

        //排气量
        tagAdapterDisplacement= new TagAdapter<String>(displacementList)
        {
            @Override
            public View getView(FlowLayout parent, int position, String s)
            {
                TextView tv = (TextView) mInflater.inflate(R.layout.tag_car_config, tagFlowDisplacement, false);
                tv.setText(s);
                return tv;
            }
        };
        tagFlowDisplacement.setAdapter(tagAdapterDisplacement);
        tagFlowDisplacement.setOnTagClickListener(new TagFlowLayout.OnTagClickListener()
        {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent)
            {
                //Toast.makeText(CarConfigSelectView.this.getContext(), displacementList.get(position), Toast.LENGTH_SHORT).show();
                String displacementSelected = displacementList.get(position);
                if(displacementSelected.equals(self.displacementSelected)){
                    //如果包含此条件，则去除此条件
                    for (int i = 0; i < selectedCondition.size(); i++) {
                        if(selectedCondition.get(i).startsWith("排气量:")){
                            selectedCondition.remove(i);
                            break;
                        }
                    }
                    //将选中状态置为未选中状态并重置所有选项(所有选项中保持之前的选中状态)
                    self.displacementSelected = "";
                    //resetConfig(self.displacementSelected);

                    setConfigListBySelection(selectedCondition);
                    setSelectedList();
                    refresh();
                }else{
                    //如果不包含此条件，则添加此条件
                    boolean has = false;
                    for (int i = 0; i < selectedCondition.size(); i++) {
                        if(selectedCondition.get(i).startsWith("排气量:")){
                            has = true;
                            break;
                        }
                    }
                    if(!has){
                        selectedCondition.add("排气量:"+displacementSelected);
                    }

                    self.displacementSelected = displacementSelected;
                    //getConfigByDisplacement(displacementSelected);

                    setConfigListBySelection(selectedCondition);
                    setSelectedList();
                    refresh();
                }
                return true;
            }
        });

    }

    /**
     * 请求配置
     * @param modelId
     */
    private void requestConfig(int modelId){
        carConfigSelectPresenter.requestCarConfig(modelId);
    }

    private void setPicAdapter() {
        convenientBanner.setPages(
                new CBViewHolderCreator<NetworkImageHolderView>() {
                    @Override
                    public NetworkImageHolderView createHolder() {
                        return new NetworkImageHolderView();
                    }
                }, details.getCarPicList());

        convenientBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {//查看大图
                Intent intent = new Intent(CarTypeSelectActivity.this, PhotoForNetActivity.class);
                intent.putExtra("piclists", details);
                intent.putExtra("position", position);
                intent.putExtra("isZonghe", true);
                startActivity(intent);
            }
        });
    }


    class NetworkImageHolderView implements Holder<CarDetails.CarPicListEntity> {
        private ImageView imageView;
        private TextView title;

        @Override
        public View createView(Context context) {
            //你可以通过layout文件来创建，也可以像我一样用代码创建，不一定是Image，任何控件都可以进行翻页
            View view = LayoutInflater.from(context).inflate(R.layout.taskdetail_photo, null);
            imageView = (ImageView) view.findViewById(R.id.photo_img);
            title = (TextView) view.findViewById(R.id.title);
            return view;
        }

        @Override
        public void UpdateUI(Context context, int position, CarDetails.CarPicListEntity data) {
            int tag = position + 1;
            title.setText(data.getItemName18() + "(" + tag + "/" + details.getCarPicList().size() + ")");
            ImageLoader.getInstance().displayImage
                    (data.getPath(), imageView, appContext.options);
        }
    }


    @OnClick({R.id.rlBrandSeries,R.id.tv_right,R.id.rlProductDate,R.id.crbNext,R.id.tvRetry})
    public void onClick(View view){
        //加入防重击
        if(!noDoubleClick.canClick()){
            return;
        }

        switch (view.getId()){
            case R.id.tv_right:
                ActivityHelp.startActivity(this, BrandActivity.class);
                break;
            case R.id.rlBrandSeries:
                Intent intent = new Intent(this,BrandSeriesActivity.class);
                startActivityForResult(intent,REQUEST_BRAND_SEREIS);
                break;
            case R.id.rlProductDate:
                chooseTime(Constant.TIME_CHUCHANG);
                break;
            case R.id.crbNext:

                boolean isFill = check();
                if(!isFill){
                    return;
                }

                intent = new Intent(CarTypeSelectActivity.this, CarDifferenceConfigSelectActivity.class);
                intent.putExtra("vin",vin);
                intent.putExtra("plateType",plateType);
                intent.putExtra("details",details);
                intent.putExtra("brandSeries",carTypeBean);
                intent.putExtra("productDate",tvProductDate.getText());
                intent.putExtra("gear",gearSelected);
                intent.putExtra("drivingMode",drivingModeSelected);
                intent.putExtra("displacement",displacementSelected);
                startActivity(intent);
                break;
            case R.id.tvRetry:
                resetConfig();
                break;
        }
    }

    /**
     * 检查数据是否都已填完
     * @return
     */
    private boolean check(){
        if(TextUtils.isEmpty(tvBrandSeriesValue.getText())){
            //MyToast.showShort("请选择品牌车系");
            setNextDisable();
            return false;
        }
        if(TextUtils.isEmpty(tvProductDate.getText())){
            //MyToast.showShort("请选择出厂日期");
            setNextDisable();
            return false;
        }
        if(TextUtils.isEmpty(gearSelected)){
            //MyToast.showShort("请选择变速箱");
            setNextDisable();
            return false;
        }
        if(TextUtils.isEmpty(drivingModeSelected)){
            //MyToast.showShort("请选择驱动方式");
            setNextDisable();
            return false;
        }
        if(TextUtils.isEmpty(displacementSelected)){
            //MyToast.showShort("请选择变速箱");
            setNextDisable();
            return false;
        }
        setNextEnable();
        return true;
    }

    private void setNextDisable(){
        crbNext.setVisibility(View.GONE);
        btnNextError.setVisibility(View.VISIBLE);
    }

    private void setNextEnable(){
        crbNext.setVisibility(View.VISIBLE);
        btnNextError.setVisibility(View.GONE);
    }

    private void getCurrentDate() {
        Calendar c = Calendar.getInstance();
        currentYear = c.get(Calendar.YEAR);
        currentMonth = c.get(Calendar.MONTH) + 1;
        String lowerYear = details.getLowYear();
        if(TextUtils.isEmpty(lowerYear)){
            MinYEAR = 1990;//currentYear - 25;
        }else{
            MinYEAR = StringUtils.getYear4String(lowerYear);
        }

    }

    /**
     * 弹出选择时间,包括年、月
     *
     * @param requestCode
     */
    private void chooseTime(int requestCode) {
        try {

            Intent in = new Intent(this, SheetTimeAty.class);
            in.putExtra("Maxyear", currentYear);
            in.putExtra("Minyear", MinYEAR);
            in.putExtra("MaxMonth", currentMonth);
            in.putExtra("MinMonth", 1);
            in.putExtra("CurMonth", currentMonth);
            in.putExtra(Constant.KEY_TITLE, "请选择出厂日期");
            startActivityForResult(in, requestCode);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "请重新选择品牌车型！", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case REQUEST_BRAND_SEREIS:
                if(data==null){
                    return;
                }
                CarTypeModel.DataBean carTypeModelBean = (CarTypeModel.DataBean) data.getSerializableExtra("carTypeModelBean");
                if(carTypeModelBean==null){
                    return;
                }
                tvBrandSeriesValue.setText(carTypeModelBean.getMakeName()+carTypeModelBean.getModelName());
                carTypeBean = carTypeModelBean;

                //请求配置
                requestConfig(carTypeModelBean.getModelID());
                break;
            case Constant.TIME_CHUCHANG:
                if(data==null){
                    return;
                }
                int year = data.getIntExtra("year", currentYear);
                int month = data.getIntExtra("month", 1);
                if (month < 10) {
                    tvProductDate.setText(year + "-0" + month);
                } else {
                    tvProductDate.setText(year + "-" + month);
                }
                check();
                break;
        }
    }

    private void addGearSelectedCon(){
        //如果不包含此条件，则添加此条件
        boolean has = false;
        for (int i = 0; i < selectedCondition.size(); i++) {
            if(selectedCondition.get(i).startsWith("变速箱:")){
                has = true;
                break;
            }
        }
        if(!has){
            selectedCondition.add("变速箱:"+gearSelected);
        }
    }

    private void addDrivingModeSelectedCon(){
        //如果不包含此条件，则添加此条件
        boolean has = false;
        for (int i = 0; i < selectedCondition.size(); i++) {
            if(selectedCondition.get(i).startsWith("驱动方式:")){
                has = true;
                break;
            }
        }
        if(!has){
            selectedCondition.add("驱动方式:"+drivingModeSelected);
        }
    }

    private void addDisplacementSelectedCon(){
        //如果不包含此条件，则添加此条件
        boolean has = false;
        for (int i = 0; i < selectedCondition.size(); i++) {
            if(selectedCondition.get(i).startsWith("排气量:")){
                has = true;
                break;
            }
        }
        if(!has){
            selectedCondition.add("排气量:"+displacementSelected);
        }
    }


    /**
     * 根据选中的变速箱，找出符合的驱动方式和排气量
     */
    private void setConfigListBySelection(ArrayList selectedCondition){

        //清空所有选项数据
        clearConfigData();

        int size = selectedCondition.size();
        if(size==0){
            //重置
            List<CarConfigModel.MemberValueBean> memberValueBeanList = carConfigModel.getData();
            for (int i = 0; i < memberValueBeanList.size(); i++) {
                CarConfigModel.MemberValueBean memberValueBean = memberValueBeanList.get(i);
                //变速箱
                String gear = memberValueBean.getGear();
                addGear(gear);
                //驱动方式
                String drivingMode = memberValueBean.getDrivingMode();
                addDrivingMode(drivingMode);
                //排气量
                String displacement = memberValueBean.getDisplacement();
                addDisplacement(displacement);
            }
        }else if(size==1){
            String config = selectedCondition.get(0).toString().split(":")[0];
            String configValue = selectedCondition.get(0).toString().split(":")[1];
            if(config.equals("变速箱")){
                gearList.add(configValue);
                //查找此变速箱条件下的驱动方式和排气量
                List<CarConfigModel.MemberValueBean> memberValueBeanList = carConfigModel.getData();
                for (int j = 0; j < memberValueBeanList.size(); j++) {
                    CarConfigModel.MemberValueBean memberValueBean = memberValueBeanList.get(j);
                    //变速箱
                    String gear = memberValueBean.getGear();
                    if(gear.equals(configValue)){
                        //驱动方式
                        String drivingMode = memberValueBean.getDrivingMode();
                        addDrivingMode(drivingMode);
                        //排气量
                        String displacement = memberValueBean.getDisplacement();
                        addDisplacement(displacement);
                    }
                }
            }else if(config.equals("驱动方式")){
                drivingModeList.add(configValue);
                //获取此驱动方式下的所有变速箱和排气量
                List<CarConfigModel.MemberValueBean> memberValueBeanList = carConfigModel.getData();
                for (int i = 0; i < memberValueBeanList.size(); i++) {
                    CarConfigModel.MemberValueBean memberValueBean = memberValueBeanList.get(i);
                    //驱动方式
                    String drivingMode = memberValueBean.getDrivingMode();
                    if(drivingMode.equals(configValue)){
                        //变速箱
                        String gear = memberValueBean.getGear();
                        addGear(gear);
                        //排气量
                        String displacement = memberValueBean.getDisplacement();
                        addDisplacement(displacement);
                    }
                }
            }else if(config.equals("排气量")){
                displacementList.add(configValue);
                //获取此排气量下的所有变速箱和驱动方式
                List<CarConfigModel.MemberValueBean> memberValueBeanList = carConfigModel.getData();
                for (int i = 0; i < memberValueBeanList.size(); i++) {
                    CarConfigModel.MemberValueBean memberValueBean = memberValueBeanList.get(i);
                    //排气量
                    String dispalcement = memberValueBean.getDisplacement();
                    if(dispalcement.equals(configValue)){
                        //变速箱
                        String gear = memberValueBean.getGear();
                        addGear(gear);
                        //驱动方式
                        String drivingMode = memberValueBean.getDrivingMode();
                        addDrivingMode(drivingMode);
                    }
                }
            }
        }else if(size==2){
            //得到选中的项
            HashMap<String,String> configMap = new HashMap<>();
            for (int i = 0; i < selectedCondition.size(); i++) {
                String config = selectedCondition.get(i).toString().split(":")[0];
                String configValue = selectedCondition.get(i).toString().split(":")[1];
                configMap.put(config, configValue);
            }
            //根据选中项，得到未选中项
            List<CarConfigModel.MemberValueBean> memberValueBeanList = carConfigModel.getData();
            for (int i = 0; i < memberValueBeanList.size(); i++) {
                CarConfigModel.MemberValueBean memberValueBean = memberValueBeanList.get(i);
                if(configMap.containsKey("变速箱")){
                    //添加变速箱
                    addGear(configMap.get("变速箱"));
                    //变速箱
                    String gear = memberValueBean.getGear();
                    if(configMap.get("变速箱").equals(gear)){
                        //驱动方式
                        if(configMap.containsKey("驱动方式")){
                            //添加驱动方式
                            addDrivingMode(configMap.get("驱动方式"));
                            String drivingMode = memberValueBean.getDrivingMode();
                            if(configMap.get("驱动方式").equals(drivingMode)){
                                //满足条件，将对应的排气量加入
                                //变速箱
                                String displacement = memberValueBean.getDisplacement();
                                addDisplacement(displacement);
                                //判断下一个
                                continue;
                            }else{
                                //判断下一个
                                continue;
                            }
                        }else{
                            //排气量
                            if(configMap.containsKey("排气量")){
                                //添加排气量
                                addDisplacement(configMap.get("排气量"));

                                String displacement = memberValueBean.getDisplacement();
                                if(configMap.get("排气量").equals(displacement)){
                                    //满足条件，将对应的驱动方式加入
                                    //驱动方式
                                    String drivingMode = memberValueBean.getDrivingMode();
                                    addDrivingMode(drivingMode);
                                    //判断下一个
                                    continue;
                                }
                            }else{
                                MyToast.showShort("选中两项条件出错 只有变速箱");
                                break;
                            }
                        }
                    }else {
                        continue;
                    }
                }else {
                    if (configMap.containsKey("驱动方式")) {
                        //添加驱动方式
                        addDrivingMode(configMap.get("驱动方式"));

                        //驱动方式
                        String drivingMode = memberValueBean.getDrivingMode();
                        if (configMap.get("驱动方式").equals(drivingMode)) {
                            //排气量
                            String displacement = memberValueBean.getDisplacement();
                            if (configMap.containsKey("排气量")) {
                                //添加排气量
                                addDisplacement(configMap.get("排气量"));

                                if (configMap.get("排气量").equals(displacement)) {
                                    //满足条件，将对应的变速箱加入
                                    //变速箱
                                    String gear = memberValueBean.getGear();
                                    addGear(gear);
                                    //判断下一个
                                    continue;
                                }
                            }else {
                                MyToast.showShort("选中两项条件出错 只有驱动方式");
                                break;
                            }

                        }else {
                            continue;
                        }
                    } else {
                        MyToast.showShort("选中两项条件出错 最多只包含排气量一项");
                        break;
                    }
                }


            }
        }else if(size==3){
            for (int i = 0; i < selectedCondition.size(); i++) {
                String config = selectedCondition.get(i).toString().split(":")[0];
                String configValue = selectedCondition.get(i).toString().split(":")[1];
                if(config.equals("变速箱")) {
                    gearList.add(configValue);
                }else if(config.equals("驱动方式")){
                    drivingModeList.add(configValue);
                }else if(config.equals("排气量")){
                    displacementList.add(configValue);
                }
            }
        }
    }

    private void addGear(String gear){
        if(!gearList.contains(gear)){
            if(!TextUtils.isEmpty(gear)) {
                gearList.add(gear);
            }
        }
    }
    private void addDrivingMode(String drivingMode){
        if(!drivingModeList.contains(drivingMode)){
            if(!TextUtils.isEmpty(drivingMode)) {
                drivingModeList.add(drivingMode);
            }
        }
    }
    private void addDisplacement(String displacement){
        if(!displacementList.contains(displacement)){
            if(!TextUtils.isEmpty(displacement)){
                displacementList.add(displacement);
            }
        }
    }

    /**
     * 清空所有选项数据
     * @author zealjiang
     * @time 2016/11/4 11:19
     */
    private void clearConfigData(){
        gearList.clear();
        drivingModeList.clear();
        displacementList.clear();
    }

    /**
     * 如果该选项下只有一项，则设置该项为选中项;
     * 或如果该选项下有多个选项，则选中上次选中的项;
     * 或如果都有一项被选中，则只显示选中的项;
     * @author zealjiang
     * @time 2017/03/20 11:18
     */
    private void setSelectedList(){
        //清空所有默认选中项
        HashSet<Integer> set = new HashSet<>();
        tagAdapterGear.setSelectedList(set);
        tagAdapterDrivingMode.setSelectedList(set);
        tagAdapterDisplacement.setSelectedList(set);

        //如果该选项下只有一项，则设置该项为选中项;如果同一类选项下有一项被选中，则不显示此类下的其它项
        //变速箱
        if(gearList.size()==1){
            tagAdapterGear.setSelectedList(0);
            gearSelected = gearList.get(0);
        }

        //驱动方式
        if(drivingModeList.size()==1){
            tagAdapterDrivingMode.setSelectedList(0);
            drivingModeSelected = drivingModeList.get(0);
        }

        //排气方式
        if(displacementList.size()==1){
            tagAdapterDisplacement.setSelectedList(0);
            displacementSelected = displacementList.get(0);
        }
    }


    /**
     * 刷新参数选择
     * @author zealjiang
     * @time 2016/11/4 11:08
     */
    private void refresh(){
        //刷新参数选择
        tagAdapterGear.notifyDataChanged();
        tagAdapterDrivingMode.notifyDataChanged();
        tagAdapterDisplacement.notifyDataChanged();

        check();
    }

    /**
     * 清空选中的配置选项
     * @author zealjiang
     * @time 2016/11/4 14:33
     */
    private void clearSelectedConfig(){
        gearSelected = "";//变速箱当前选中项
        drivingModeSelected = "";//驱动方式当前选中项
        displacementSelected = "";//排气量当前选中项
    }

    /**
     * 重置 车辆配置（变速箱、排气量、驱动方式）
     */
    public void resetConfig(){

        //清空所有选中条件
        selectedCondition.clear();

        //清空所有选项数据
        clearConfigData();

        List<CarConfigModel.MemberValueBean> memberValueBeanList = carConfigModel.getData();
        for (int i = 0; i < memberValueBeanList.size(); i++) {
            CarConfigModel.MemberValueBean memberValueBean = memberValueBeanList.get(i);
            //变速箱
            String gear = memberValueBean.getGear();
            addGear(gear);
            //驱动方式
            String drivingMode = memberValueBean.getDrivingMode();
            addDrivingMode(drivingMode);
            //排气量
            String displacement = memberValueBean.getDisplacement();
            addDisplacement(displacement);
        }

        //清空选中的配置选项
        clearSelectedConfig();

        //设置默认选中项
        setSelectedList();

        //刷新参数选择
        refresh();

    }

    @Override
    public void brandSeriesSuccess(CarTypeModel suc) {
        if(suc.getData()==null){
            return;
        }
        int size = suc.getData().size();
        if(size==0||size>1){
            MyToast.showShort("请选择品牌车系");
            tvHintError.setVisibility(View.VISIBLE);
        }else{
            tvHintError.setVisibility(View.GONE);
            carTypeBean = suc.getData().get(0);
            tvBrandSeriesValue.setText(carTypeBean.getMakeName()+carTypeBean.getModelName());

            //请求配置
            requestConfig(carTypeBean.getModelID());
        }

    }

    @Override
    public void brandSeriesFail(String string) {
        MyToast.showShort(string);


        tvHintError.setVisibility(View.VISIBLE);
    }

    @Override
    public void carConfigSucceed(CarConfigModel carConfigModel) {

        //初始化参数
        if(null==carConfigModel){
            return;
        }
        if(carConfigModel.getData().size()==0){
            return;
        }
        //显示配置项
        llCarConfig.setVisibility(View.VISIBLE);

        //清空所有选项数据
        clearConfigData();

        //清空所有选中条件
        selectedCondition.clear();

        this.carConfigModel = carConfigModel;
        List<CarConfigModel.MemberValueBean> memberValueBeanList = carConfigModel.getData();
        for (int i = 0; i < memberValueBeanList.size(); i++) {
            CarConfigModel.MemberValueBean memberValueBean = memberValueBeanList.get(i);
            //变速箱
            String gear = memberValueBean.getGear();
            addGear(gear);
            //驱动方式
            String drivingMode = memberValueBean.getDrivingMode();
            addDrivingMode(drivingMode);
            //排气量
            String displacement = memberValueBean.getDisplacement();
            addDisplacement(displacement);
        }

        //清空选中的配置选项
        clearSelectedConfig();

        //设置默认选中项
        setSelectedList();

        //刷新参数选择
        refresh();

        check();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
        if (carTypeSelectPresenter != null)
            carTypeSelectPresenter.detachView();
    }
}
